<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.roleName"
        class="filter-item"
        clearable
        placeholder="角色名称"
        style="width: 150px;"
        @keyup.enter.native="handleFilter"
      />
      <el-button
        v-waves
        v-permission="['sys:role:list']"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >搜索</el-button>
      <el-button
        v-waves
        v-permission="['sys:role:save']"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreate"
      >添加</el-button>
    </div>

    <el-table :key="tableKey" :data="list" fit highlight-current-row style="width: 100%;">
      <el-table-column label="角色ID" prop="id" width="70px" align="center" />
      <el-table-column label="角色名称" prop="roleName" align="center" />
      <el-table-column label="部门名称" prop="deptName" align="center" />
      <!-- <el-table-column label="功能权限" prop="remark" align="center" /> -->
      <el-table-column label="创建时间" prop="createdAt" width="140px" align="center" />
      <el-table-column label="操作" align="center" width="150px">
        <template slot-scope="{row}">
          <el-button
            v-waves
            v-permission="['sys:role:update']"
            type="primary"
            icon="el-icon-edit"
            @click="handleUpdate(row)"
          />
          <!-- <el-button
            v-waves
            v-permission="['sys:role:delete']"
            icon="el-icon-delete"
            type="danger"
            @click="handleDelete(row)"
          /> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNo"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />

    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      top="2vh"
      width="500px"
    >
      <el-form
        ref="dataForm"
        :model="role"
        :rules="rules"
        label-position="right"
        label-width="100px"
        style="width:90%"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="role.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <!-- <el-form-item label="部门名称" prop="deptId">
          <el-cascader
            v-model="role.deptId"
            :options="deptList"
            :props="deptProps"
            clearable
            :show-all-levels="false"
            style="width:310px"
          />
        </el-form-item> -->
        <el-form-item label="功能权限" prop="menuIdList">
          <el-cascader
            ref="cascader"
            v-model="role.menuIdList"
            :options="menuList"
            :props="defaultProps"
            clearable
            collapse-tags
            style="width:310px"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="role.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getList, get, create, update, del } from '@/api/system/role'
import { getMenuList } from '@/api/system/menu'
import { getDeptList } from '@/api/system/dept'
import waves from '@/directive/waves' // Waves directive
export default {
  name: 'RoleTable',
  directives: { waves },
  filters: {},
  data() {
    return {
      tableKey: 0,
      list: [],
      total: 0,
      listQuery: {
        pageNo: 1,
        pageSize: 10,
        orderByField: 'createdAt',
        orderBy: 'desc'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '更新',
        create: '新增'
      },
      role: {
        deptId: 1,
        menuIdList: []
      },
      rules: {
       // roleName: [ { required: true, message: '请输入角色名称', trigger: 'blur' } ],

        roleName: [
          {
            required: true,
            validator: (rule, value, callback) => {
            
               if (value == null){
              callback('角色名不能为空')
               } else
              if (value.length>10) {
                callback('角色名不能大于10个字')   //
              }  else if(/[^\u4e00-\u9fa5]/.test(value)){
                 callback(new Error('必须是中文且不能有空格!'))
              }
              else   {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
    //  roleName: [ { required: true, message: '请输入角色名称', trigger: 'blur' } 
    //           ,
    //         { min: 0, max: 10, message: '角色名称不能大于10个字符', trigger: 'blur' }

    //       ],
       // deptId: [{ required: true, message: '请选择部门', trigger: 'blur' }],
        menuIdList: [{ required: true, message: '请选择角色', trigger: 'blur' }]
      },
      menuList: [],
      deptList: [],
      deptProps: {
        expandTrigger: 'hover',
        checkStrictly: true,
        emitPath: false,
        children: 'children',
        label: 'name',
        value: 'id'
      },
      defaultProps: {
        expandTrigger: 'hover',
        emitPath: false,
        children: 'children',
        label: 'name',
        value: 'id',
        multiple: true
      }
    }
  },
  created() {
    this.getList()
    this.getMenuList()
   // this.getDeptList()
  },
  methods: {
    getMenuList() {
      getMenuList().then(response => {
        this.menuList = response
      })
    },
    // getDeptList() {
    //   getDeptList().then(response => {
    //     this.deptList = response
    //   })
    // },
    // 获取数据
    getList() {
      getList(this.listQuery).then(response => {
        this.list = response.list
        this.total = response.totalCount
      })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    resetTemp() {
      this.$nextTick(() => {
        this.role = {
          deptId: null,
          menuIdList: []
        }
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleCreate() {
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.resetTemp()
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          var nodes = this.$refs['cascader'].getCheckedNodes()
          for (var i = 0; i < nodes.length; i++) {
            this.role.menuIdList = Array.from(
              new Set(this.role.menuIdList.concat(nodes[i].path))
            )
          }
          this.role.deptId=1 
          create(this.role).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.getMenuList()
            this.getDeptList()
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.resetTemp()
      get(row.id).then(response => {
        this.role = response
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          var nodes = this.$refs['cascader'].getCheckedNodes()
          for (var i = 0; i < nodes.length; i++) {
            this.role.menuIdList = Array.from(
              new Set(this.role.menuIdList.concat(nodes[i].path))
            )
          }
          this.role.deptId=1 
          update(this.role).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.getMenuList()
            this.getDeptList()
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del([row.id]).then(response => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
          this.getMenuList()
          this.getDeptList()
        })
      })
    }
  }
}
</script>
